#include "main.h"
#include <windows.h>

typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
typedef void (WINAPI *LPFN_GETNATIVESYSTEMINFO) (LPSYSTEM_INFO);

typedef enum {
    UNKNOWN = 0
    , SYSINFO_32PROCESS = 1
    , SYSINFO_32PROCESS_ON_WO64 = 2
    , SYSINFO_64PROCESS = 3
} BaseSystemInfo;

BOOL Isx64Architecture(void)
{
    LPFN_GETNATIVESYSTEMINFO fnGetNativeSystemInfo=NULL;
    BOOL bIsx64 = FALSE;
    SYSTEM_INFO info;

    if (fnGetNativeSystemInfo == NULL) {
        fnGetNativeSystemInfo = (LPFN_GETNATIVESYSTEMINFO) GetProcAddress(
            GetModuleHandle(TEXT("kernel32")), TEXT("GetNativeSystemInfo"));
    }

    if (fnGetNativeSystemInfo != NULL) {
        fnGetNativeSystemInfo(&info);
        if (info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
            bIsx64 = TRUE;
        } else if (info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) {
            bIsx64 = TRUE;
        } else if (info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) {
            bIsx64 = FALSE;
        }
    }
    return bIsx64;
}

BOOL IsWow64(HANDLE processHandle)
{
    LPFN_ISWOW64PROCESS fnIsWow64Process=NULL;
    BOOL bIsWow64 = FALSE;

    if (fnIsWow64Process == NULL) {
        fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
            GetModuleHandle(TEXT("kernel32")), TEXT("IsWow64Process"));
    }

    if (fnIsWow64Process != NULL) {
        if (!fnIsWow64Process(processHandle, &bIsWow64)) {
            return FALSE;
        }
    }
    return bIsWow64;
}

BaseSystemInfo GetBaseSystemInfo(HANDLE processHandle)
{
    if (IsWow64(processHandle) == FALSE) {
        return SYSINFO_32PROCESS;
    } else if (Isx64Architecture() == TRUE) {
        return SYSINFO_64PROCESS;
    } else {
        return SYSINFO_32PROCESS_ON_WO64;
    }
}

int main(int argc, TCHAR* argv[])
{
    switch (GetBaseSystemInfo(GetCurrentProcess())) {
        case SYSINFO_32PROCESS_ON_WO64:
            //printf("WOW64");
			if(argc == 1){
				WinExec("LookbackAdapter32.exe", SW_SHOW);
			}
			else if(argc==2 && strcmp(argv[1],TEXT("-addIP"))==0){
				WinExec("LookbackAdapter32.exe -addIP", SW_SHOW);
			}
            break;
        case SYSINFO_64PROCESS:
            //printf("x64");
			if(argc == 1){
				WinExec("LookbackAdapter64.exe", SW_SHOW);
			}
			else if(argc==2 && strcmp(argv[1],TEXT("-addIP"))==0){
				WinExec("LookbackAdapter64.exe -addIP", SW_SHOW);
			}
            break;
        case SYSINFO_32PROCESS:
			if(argc == 1){
				WinExec("LookbackAdapter32.exe", SW_SHOW);
			}
			else if(argc==2 && strcmp(argv[1],TEXT("-addIP"))==0){
				WinExec("LookbackAdapter32.exe -addIP", SW_SHOW);
			}
            break;
    }
    return 0;
}
